package com.zlyx.easy.core.tool;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.zlyx.easy.core.map.Maps;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * <p>
 * 驼峰下划线互转工具类
 * </p>
 *
 * @author 赵光
 * @since 2018年11月16日
 */
public final class CamelTool {

	private static Map<String, String> map = Maps.newConcurrentHashMap();

	/**
	 * 下划线转驼峰法
	 * 
	 * @param line       源字符串
	 * @param smallCamel 大小驼峰,是否为小驼峰
	 * @return 转换后的字符串
	 */
	public static String underline2Camel(String line) {
		if (line == null || "".equals(line)) {
			return "";
		}
		String res = map.get(line);
		if (StringUtils.isEmpty(res)) {
			StringBuffer sb = new StringBuffer();
			Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
			Matcher matcher = pattern.matcher(line);
			while (matcher.find()) {
				String word = matcher.group();
				sb.append(matcher.start() == 0 ? Character.toLowerCase(word.charAt(0))
						: Character.toUpperCase(word.charAt(0)));
				int index = word.lastIndexOf('_');
				if (index > 0) {
					sb.append(word.substring(1, index).toLowerCase());
				} else {
					sb.append(word.substring(1).toLowerCase());
				}
			}
			res = sb.toString();
			map.put(line, res);
		}
		return res;
	}

	/**
	 * 驼峰法转下划线
	 * 
	 * @param line 源字符串
	 * @return 转换后的字符串
	 */
	public static String camel2Underline(String line) {
		if (line == null || "".equals(line)) {
			return "";
		}
		String res = map.get(line);
		if (StringUtils.isEmpty(res)) {
			line = String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
			StringBuffer sb = new StringBuffer();
			Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
			Matcher matcher = pattern.matcher(line);
			while (matcher.find()) {
				String word = matcher.group();
				sb.append(word.toLowerCase());
				sb.append(matcher.end() == line.length() ? "" : "_");
			}
			res = sb.toString();
			map.put(line, res);
		}
		return res;
	}
}
